<?php
/* 
 * 加载设置面板
 * 如果需要加载子主题，请使用stylesheet_directory
 * instead of template_directory
 */
 define ( '_IST802_VERSION',1.0);
if ( !function_exists( 'optionsframework_init' ) ) {
	define( 'OPTIONS_FRAMEWORK_DIRECTORY', get_template_directory_uri() . '/inc/' );
	require_once dirname( __FILE__ ) . '/inc/options-framework.php';
}


 /*** 博客函数开始 ***/
  
 //侧栏小工具
require_once(TEMPLATEPATH . '/ist/widgets.php');
//yigujin
require_once(TEMPLATEPATH . '/ist/comment-template.php');
//require_once(TEMPLATEPATH . '/ist/comment-ajax.php');
//图标美化
include("ist/awesome/main.php");
//附加函数文件
include_once('function_ist.php');

//改用多说gravatar服务器
function get_ssl_avatar($avatar) {
  $avatar = preg_replace('/.*\/avatar\/(.*)\?s=([\d]+)&.*/','<img src="https://secure.gravatar.com/avatar/$1?s=$2" class="avatar avatar-$2" height="$2" width="$2">',$avatar);
  return $avatar;
}
add_filter('get_avatar', 'get_ssl_avatar');
// 移除头部冗余代码
remove_action( 'wp_head', 'wp_generator' );// WP版本信息
remove_action( 'wp_head', 'rsd_link' );// 离线编辑器接口
remove_action( 'wp_head', 'wlwmanifest_link' );// 同上
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 );// 上下文章的url
remove_action( 'wp_head', 'feed_links', 2 );// 文章和评论feed
remove_action( 'wp_head', 'feed_links_extra', 3 );// 去除评论feed
remove_action( 'wp_head', 'wp_shortlink_wp_head', 10, 0 );// 短链接
remove_action( 'wp_head','print_emoji_detection_script',7);     //解决4.2版本部分主题大量404请求问题
remove_action('admin_print_scripts', 'print_emoji_detection_script'); //解决后台404请求
remove_action( 'wp_print_styles',   'print_emoji_styles'    );  //移除4.2版本前台表情样式钩子
remove_action( 'admin_print_styles',    'print_emoji_styles');  //移除4.2版本后台表情样式钩子
remove_action( 'the_content_feed',      'wp_staticize_emoji');  //移除4.2 emoji相关钩子
remove_action( 'comment_text_rss',      'wp_staticize_emoji');  //移除4.2 emoji相关钩子
// 禁止后台加载谷歌字体
function wp_remove_open_sans_from_wp_core() {
	wp_deregister_style( 'open-sans' );
	wp_register_style( 'open-sans', false );
	wp_enqueue_style('open-sans','');
}
// 前台删除Google字体CSS 
//add_action('wp_enqueue_scripts', 'remove_wp_open_sans');
// 后台删除Google字体CSS 
//add_action('admin_enqueue_scripts', 'remove_wp_open_sans'); 

add_action( 'init', 'wp_remove_open_sans_from_wp_core' );
//禁用静态资源查询
function _remove_script_version( $src ){
    $parts = explode( '?', $src );
    return $parts[0];
}
add_filter( 'script_loader_src', '_remove_script_version', 15, 1 );
add_filter( 'style_loader_src', '_remove_script_version', 15, 1 );
// 阻止站内文章Pingback
function tin_noself_ping(&$links) {
    $home = get_option('home');
    foreach ($links as $l => $link) if (0 === strpos($link, $home)) unset($links[$l]);
}
//隐藏admin Bar
function hide_admin_bar($flag) {
    return false;
}
add_filter('show_admin_bar', 'hide_admin_bar');

//添加后台左下角文字
function ist_footer_text($text) {
    $text = '感谢使用<a target="_blank" href="http://www.ist-802.net/" >吾爱笔记</a>主题';
    return $text;
}
add_filter('admin_footer_text', 'ist_footer_text');

//注册菜单
if(!function_exists('ist_register_nav_menu')){
	function ist_register_nav_menu() {
		register_nav_menus(
			array(
				'navleft'	=>	__('左菜单'), // Register the Primary menu
				// Copy and paste the line above right here if you want to make another menu,
				// just change the 'primary' to another name
				'navright'   => __('右菜单 两个/三个最佳')
			)
		);
	}
}
add_action( 'after_setup_theme', 'ist_register_nav_menu' );

//小工具
function ist_thumbnail_src(){ 
    global $post; 
    if( $values = get_post_custom_values("thumb") ) {    //输出自定义域图片地址 
        $values = get_post_custom_values("thumb"); 
        $post_thumbnail_src = $values [0]; 
    } elseif( has_post_thumbnail() ){    //如果有特色缩略图，则输出缩略图地址 
        $thumbnail_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID),'full'); 
        $post_thumbnail_src = $thumbnail_src [0]; 
    } else { 
        $post_thumbnail_src = ''; 
        ob_start(); 
        ob_end_clean(); 
        $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
        $post_thumbnail_src = $matches [1] [0];   //获取该图片 src 
        if(empty($post_thumbnail_src)){    //如果日志中没有图片，则显示thumbnail/random下的随机图片 
            $random = mt_rand(1, 7); 
            echo get_bloginfo('template_url'); 
            echo '/images/random/tp'.$random.'.jpg'; 
        } 
    }; 
    echo $post_thumbnail_src; 
} 
//定义缩略图—（特效） 
function ist_thumte($timthumb_w,$timthumb_h){ 

    echo '<a href="'.get_permalink().'" title="'.get_the_title().'"><div class="img">'; 
    if( of_get_option('ist_tim_s') ){
        echo '<img ';
        /*if (get_opt('lazyload_s')){
            echo 'src="'.get_bloginfo('template_directory').'/images/loading.gif" data-original=';
        }else{*/
            echo 'src';
        /*}*/
        echo '="'.get_template_directory_uri().'/timthumb.php?src=';
        echo ist_thumbnail_src();
        echo '&h='.$timthumb_h.'&w='.$timthumb_w.'&zc=1" alt="'.get_the_title().'" title="'.get_the_title().'" data-animate="bounceIn"/>';}
        else {
            echo '<img ';
            /*if (get_opt('lazyload_s')){
                echo 'src="'.get_bloginfo('template_directory').'/images/loading.gif" data-original='; 
            }else{*/
                echo 'src';
            /*}*/
            echo '="';
            echo ist_thumbnail_src();
            echo '" alt="'.get_the_title().'" title="'.get_the_title().'" data-animate="bounceIn" height="70" width="70"/>';}
    echo '</div></a>';
 }
 /*
 function ist_sy($timthumb_w,$timthumb_h){ 

 }*/
 //时间显示方式‘xx以前’
function time_ago($type = 'commennt', $day = 7) {
    $d = $type == 'post' ? 'get_post_time' : 'get_comment_time';
    if (time() - $d('U') > 60 * 60 * 24 * $day) return;
    echo ' (', human_time_diff($d('U') , strtotime(current_time('mysql', 0))) , '前)';
}
 function timeago( $ptime ) {
    $ptime = strtotime($ptime);
    $etime = time() - $ptime;
    if($etime < 1) return '刚刚';
    $interval = array (
        12 * 30 * 24 * 60 * 60  =>  '年前 ('.date('Y-m-d', $ptime).')',
        30 * 24 * 60 * 60       =>  '个月前 ('.date('m-d', $ptime).')',
        7 * 24 * 60 * 60        =>  '周前 ('.date('m-d', $ptime).')',
        24 * 60 * 60            =>  '天前',
        60 * 60                 =>  '小时前',
        60                      =>  '分钟前',
        1                       =>  '秒前'
    );
    foreach ($interval as $secs => $str) {
        $d = $etime / $secs;
        if ($d >= 1) {
            $r = round($d);
            return $r . $str;
        }
    };
}

// 自动生成英文别名
function bymt_slug_auto_translate( $title ) {
 $wp_http_get = wp_safe_remote_get( 'http://fanyi.baidu.com/v2transapi?from=zh&to=en&transtype=trans&query=' . $title );
 if ( empty( $wp_http_get->errors ) ) {
 if ( ! empty( $wp_http_get['body'] ) ) {
 $trans_result = json_decode( $wp_http_get['body'], true );
 $trans_title = $trans_result['trans_result']['data'][0]['dst'];
 return $trans_title;
 }
 }
 return;
}
add_filter( 'sanitize_title', 'bymt_slug_auto_translate', 1 );
//别名
function the_slug() {
    $post_data = get_post($post->ID, ARRAY_A);
    $slug = $post_data['post_name'];
    return $slug; 
}

// 添加一个新的列 ID
function ssid_column($cols) {
        $cols['ssid'] = 'ID';
        return $cols;
    }
// 显示 ID
function ssid_value($column_name, $id) {
        if ($column_name == 'ssid')
            echo $id;
    }
function ssid_return_value($value, $column_name, $id) {
        if ($column_name == 'ssid') 
            $value = $id;
        return $value;
    }
// 为 ID 这列添加css 
function ssid_css() { 
    ?>
    <style type="text/css">
        #ssid { width: 50px; } /* Simply Show IDs */
    </style>
    <?php   
    }
// 通过动作/过滤器输出各种表格和CSS
function ssid_add() {
        add_action('admin_head', 'ssid_css');
        add_filter('manage_posts_columns', 'ssid_column');
        add_action('manage_posts_custom_column', 'ssid_value', 10, 2);
        add_filter('manage_pages_columns', 'ssid_column');
        add_action('manage_pages_custom_column', 'ssid_value', 10, 2);
        add_filter('manage_media_columns', 'ssid_column');
        add_action('manage_media_custom_column', 'ssid_value', 10, 2);
        add_filter('manage_link-manager_columns', 'ssid_column');
        add_action('manage_link_custom_column', 'ssid_value', 10, 2);
        add_action('manage_edit-link-categories_columns', 'ssid_column');
        add_filter('manage_link_categories_custom_column', 'ssid_return_value', 10, 3);
        foreach ( get_taxonomies() as $taxonomy ) {
            add_action("manage_edit-${taxonomy}_columns", 'ssid_column');           
            add_filter("manage_${taxonomy}_custom_column", 'ssid_return_value', 10, 3);
        }
        add_action('manage_users_columns', 'ssid_column');
        add_filter('manage_users_custom_column', 'ssid_return_value', 10, 3);
        add_action('manage_edit-comments_columns', 'ssid_column');
        add_action('manage_comments_custom_column', 'ssid_value', 10, 2);
    }
add_action('admin_init', 'ssid_add');

//链接
add_filter('pre_option_link_manager_enabled','__return_true');


//分享时摘要图片
function single_post_image(){
    global $post;
    if (has_post_thumbnail($post->ID)) {
        $post_thumbnail_id = get_post_thumbnail_id( $post_id );
        $img = wp_get_attachment_image_src( $post_thumbnail_id, 'full' );
        $img = $img[0];
    }else{
        $content = $post->post_content;
        preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $content, $strResult, PREG_PATTERN_ORDER);
        if (!empty($strResult[1])) {
            $img = $strResult[1][0];
        }else{
            // $img = get_template_directory_uri() .'/images/share.jpg';
            $img = '';
        }
    }
    return $img;
}

//相关文章
function specs_relatedpost($post_num = 5) {
    global $post;
    echo '<ul>';
    $exclude_id = $post->ID;
    $posttags = get_the_tags(); $i = 0;
    if ( $posttags ) {
        $tags = ''; foreach ( $posttags as $tag ) $tags .= $tag->term_id . ',';
        $args = array(
            'post_status' => 'publish',
            'tag__in' => explode(',', $tags),
            'post__not_in' => explode(',', $exclude_id),
            'ignore_sticky_posts' => 1,
            'orderby' => 'comment_date',
            'posts_per_page' => $post_num
        );
        query_posts($args);
        while( have_posts() ) { the_post(); ?>
            <li>
                <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" target="_blank"><?php the_title(); ?></a>
            </li>
            <?php
            $exclude_id .= ',' . $post->ID; $i ++;
        }
        wp_reset_query();
    }
    if ( $i < $post_num ) {
        $cats = ''; foreach ( get_the_category() as $cat ) $cats .= $cat->cat_ID . ',';
        $args = array(
            'category__in' => explode(',', $cats),
            'post__not_in' => explode(',', $exclude_id),
            'ignore_sticky_posts' => 1,
            'orderby' => 'comment_date',
            'posts_per_page' => $post_num - $i
        );
        query_posts($args);
        while( have_posts() ) { the_post(); ?>
            <li>
                <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" target="_blank"><?php the_title(); ?></a>
            </li>
            <?php $i++;
        }
        wp_reset_query();
    }
    if ( $i  == 0 )  echo '<li>没有相关文章!</li>';
    echo '</ul>';
}

//avatar头像缓存
function my_avatar( $email = 'root@ysicing.net', $size = '40', $default = '', $alt = '') {
  $f = md5( strtolower( $email ) );
  $a = get_bloginfo('template_url') . '/images/avatar/'. $f . $size . '.png';
  $e = get_template_directory() . '/images/avatar/' . $f . $size . '.png';
  $d = get_template_directory() . '/images/avatar/' . $f . '-d.png';
  $txdf = get_bloginfo('template_url'). '/images/avatar/default.png';
  if($default=='')
    $default = $txdf;
  $t = 2592000; // 缓存有效期30天, 这里单位:秒
  if ( !is_file($e) || (time() - filemtime($e)) > $t ) {
    if ( !is_file($d) || (time() - filemtime($d)) > $t ) {
      // 验证是否有头像
      $uri = 'http://gravatar.duoshuo.com/avatar/' . $f . '?d=404';
      $headers = @get_headers($uri);
      if (!preg_match("|200|", $headers[0])) {
        // 没有头像，则新建一个空白文件作为标记
        $handle = fopen($d, 'w');
        fclose($handle);
        $a = $default;
      }
      else {
        // 有头像且不存在则更新
        $r = get_option('avatar_rating');
        $g = 'http://gravatar.duoshuo.com/avatar/'. $f. '?s='. $size. '&r=' . $r;
        copy($g, $e);
      }
    }
    else {
      $a = $default;
    }
  } 
  $avatar = "<img alt='{$alt}' src='{$a}' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />";
  return apply_filters('my_avatar', $avatar, $email, $size, $default, $alt);
}
//mark
function WelcomeCommentAuthorBack($email = ''){
    if(empty($email)){
        return;
    }
    global $wpdb;

    $past_30days = gmdate('Y-m-d H:i:s',((time()-(24*60*60*30))+(get_option('gmt_offset')*3600)));
    $sql = "SELECT count(comment_author_email) AS times FROM $wpdb->comments
                    WHERE comment_approved = '1'
                    AND comment_author_email = '$email'
                    AND comment_date >= '$past_30days'";
    $times = $wpdb->get_results($sql);
    $times = ($times[0]->times) ? $times[0]->times : 0;
    $message = $times ? sprintf(__('过去30天内您有<strong>%1$s</strong>条留言，感谢关注!' ), $times) : '您已很久都没有留言了，这次说点什么吧？';
    return $message;
}

// 评论链接新窗口
function commentauthor($comment_ID = 0) {
    $url    = get_comment_author_url( $comment_ID );
    $author = get_comment_author( $comment_ID );
    if ( empty( $url ) || 'http://' == $url )
        echo $author;
    else
        echo "<a href='$url' rel='external nofollow' target='_blank' class='url'>$author</a>";
}

 //获取访客VIP信息
/*function get_author_class($comment_author_email,$user_id){ 
global $wpdb; 
$author_count = count($wpdb->get_results( 
"SELECT comment_ID as author_count FROM $wpdb->comments WHERE comment_author_email = '$comment_author_email' ")); 
$adminEmail = get_option('admin_email');if($comment_author_email ==$adminEmail) return; 
if($author_count>=1 && $author_count<3) 
echo '<a class="vip1" title="评论达人 LV.1"></a>'; 
else if($author_count>=3 && $author_count<5) 
echo '<a class="vip2" title="评论达人 LV.2"></a>'; 
else if($author_count>=5 && $author_count<10) 
echo '<a class="vip3" title="评论达人 LV.3"></a>'; 
else if($author_count>=10 && $author_count<20) 
echo '<a class="vip4" title="评论达人 LV.4"></a>'; 
else if($author_count>=20 &&$author_count<50) 
echo '<a class="vip5" title="评论达人 LV.5"></a>'; 
else if($author_count>=50 && $author_count<100) 
echo '<a class="vip6" title="评论达人 LV.6"></a>'; 
else if($author_count>=100) 
echo '<a class="vip7" title="评论达人 LV.7"></a>'; 
}
*/
//欲思@添加编辑器快捷按钮
add_action('admin_print_scripts', 'my_quicktags');
function my_quicktags() {
    wp_enqueue_script('my_quicktags', get_stylesheet_directory_uri() . '/js/my_quicktags.js', array(
        'quicktags'
    ));
};



//当搜索/标签/目录为1时跳转到文章
function category_jump_page() { //定义函数
    if(is_category() || is_search() || is_tag()) { //判断是否是分类列表页面或者搜索结果页面
        global $wp_query; //定义全局变量
        if ($wp_query->post_count == 1) { //判断文章数量是否是1
            wp_redirect( get_permalink( $wp_query->posts['0']->ID ) ); //如果是1则使用wordpress内置函数wp_redirect跳转
        }
    }
}
add_action('template_redirect', 'category_jump_page'); //把定义的函数使用上

//维护代码

function wp_maintenance_mode(){
    if(!current_user_can('edit_themes') || !is_user_logged_in()){
   //     wp_die('网站维护中预计开放时间:遥遥无期 没事儿您就别来啦……', 'Maintenance - Could you please not disturb me ', array('response' => '503'));
    }
}
add_action('get_header', 'wp_maintenance_mode');

//过滤非中文
function refused_spam_comments( $comment_data ) {  
    $pattern = '/[一-龥]/u';  
    $jpattern ='/[ぁ-ん]+|[ァ-ヴ]+/u';
    if(!preg_match($pattern,$comment_data['comment_content'])) { 
    wp_die('写点汉字吧，博主外语很捉急！You should type some Chinese word!'); 
    } 
    if(preg_match($jpattern, $comment_data['comment_content'])){
    wp_die('日文滚粗！Japanese Get out！日本語出て行け！ You should type some Chinese word!'); 
    }
    return( $comment_data );  
}  
add_filter('preprocess_comment','refused_spam_comments');
//后台设置评论屏蔽黑名单
function v7v3_fuckspam($comment) {
    if(  is_user_logged_in()){ return $comment;} //登录用户无压力...
       
    if( wp_blacklist_check($comment['comment_author'],$comment['comment_author_email'],$comment['comment_author_url'], $comment['comment_content'], $comment['comment_author_IP'], $comment['comment_agent'] )){
        header("Content-type: text/html; charset=utf-8");
        wp_die('
您评论包含辱骂，过激或者违反法律等言论，或者您的IP已被加入黑名单，如有疑问请联系管理员处理！<a href="javascript:history.go(-1);">返回文章页</a>
');
    }  else  {
        return $comment;
    }
}
add_filter('preprocess_comment', 'v7v3_fuckspam');
//排除页面
function search_filter_page($query) {
    if ($query->is_search) {
        $query->set('post_type', 'post');
    }
    return $query;
}
add_filter('pre_get_posts', 'search_filter_page');
/*文章索引*/
function article_index($content) {
   $matches = array();
   $ul_li = '';

   $r = "/<h3>([^<]+)<\/h3>/im";

   if(is_singular() && preg_match_all($r, $content, $matches)) {
      foreach($matches[1] as $num => $title) {
         $title = trim(strip_tags($title));
         $content = str_replace($matches[0][$num], '<h3 id="title-'.$num.'">'.$title.'</h3>', $content);
         $ul_li .= '<li><a href="#title-'.$num.'" title="'.$title.'">'.$title."</a></li>\n";
      }

      $content = "\n<div id=\"article-index\">
                     <strong>Post Index</strong>
                     <ul id=\"index-ul\">\n" . $ul_li . "</ul>
                  </div>\n" . $content;
   }

   return $content;
}
add_filter( 'the_content', 'article_index' );

// 评论添加@，by Ludou
function ludou_comment_add_at( $comment_text, $comment = '') {
  if( $comment->comment_parent > 0) {
    $comment_text = '@<a href="#comment-' . $comment->comment_parent . '">'.get_comment_author( $comment->comment_parent ) . '</a> ' . $comment_text;
  }

  return $comment_text;
}
add_filter( 'comment_text' , 'ludou_comment_add_at', 20, 2);



//翻页
function ist_pagenavi() {
    global $wp_query, $wp_rewrite;
    $pages = '';
    $max = $wp_query->max_num_pages;
    if (!$current = get_query_var('paged')) $current = 1;
    $args['base'] = str_replace(999999999, '%#%', get_pagenum_link(999999999));
    $args['total'] = $max;
    $args['current'] = $current;
    $total = 1;
    $args['mid_size'] = 3;
    $args['end_size'] = 1;
    $args['prev_text'] = '&laquo;Prev';
    $args['next_text'] = 'Next&raquo;';
    if ($max > 1) echo '<div class="navigation pagination">';
    echo $pages . paginate_links($args);
    if ($max > 1) echo '</div>';
}
//UA信息  
function user_agent($ua) {  
 //开始解析操作系统  
 $os = null;  
 if (preg_match('/Windows NT 6.0/i', $ua)) {  
   $os = "Windows Vista";  
 } elseif (preg_match('/Windows NT 6.1/i', $ua)) {  
   $os = "Windows 7";  
 } elseif (preg_match('/Windows NT 6.2/i', $ua)) {  
   $os = "Windows 8";  
 } elseif (preg_match('/Windows NT 6.3/i', $ua)) {  
   $os = "Windows 8.1";  
 } elseif (preg_match('/Windows NT 10.0/i', $ua)) {  
   $os = "Windows 10";  
 } elseif (preg_match('/Windows NT 5.1/i', $ua)) {  
   $os = "Windows XP";  
 } elseif (preg_match('/Windows NT 5.2/i', $ua) && preg_match('/Win64/i', $ua)) {  
   $os = "Windows XP 64 bit";  
 } elseif (preg_match('/Android ([0-9.]+)/i',$ua,$matches)) {  
   $os = "Android " . $matches[1];  
 } elseif (preg_match('/iPhone OS ([_0-9]+)/i' , $ua , $matches)) {  
   $os = 'iPhone ' . $matches[1];  
 } elseif (preg_match('/Ubuntu/i',$ua, $matches)) {  
   $os = 'Ubuntu ';  
 } elseif (preg_match('/ Mac OS X ([0-9]+)/i',$ua, $matches)) {  
   $os = 'Mac OS ' . $matches[1];  
 } else {  
   $os = 'Kali Linux';  
 }  
 if (preg_match('#(Camino|Chimera)[ /]([a-zA-Z0-9.]+)#i', $ua, $matches)) {  
   $browser = 'Camino ' . $matches[2];  
 } elseif (preg_match('#SE 2([a-zA-Z0-9.]+)#i', $ua, $matches)) {  
   $browser = '搜狗浏览器 2' . $matches[1];  
 } elseif (preg_match('#360([a-zA-Z0-9.]+)#i', $ua, $matches)) {  
   $browser = '360浏览器 ' . $matches[1];  
 } elseif (preg_match('#Maxthon( |\/)([a-zA-Z0-9.]+)#i', $ua, $matches)) {  
   $browser = 'Maxthon ' . $matches[2];  
 } elseif (preg_match('#Chrome/([a-zA-Z0-9.]+)#i', $ua, $matches)) {  
   $browser = 'Chrome ' . $matches[1];  
 } elseif (preg_match('#XiaoMi/MiuiBrowser/([0-9.]+)#i' , $ua , $matches)) {  
   $browser = '小米浏览器 ' . $matches[1];  
 } elseif (preg_match('#Safari/([a-zA-Z0-9.]+)#i', $ua, $matches)) {  
   $browser = 'Safari ' . $matches[1];  
 } elseif (preg_match('#opera mini#i', $ua)) {  
   preg_match('#Opera/([a-zA-Z0-9.]+)#i', $ua, $matches);  
   $browser = 'Opera Mini ' . $matches[1];  
 } elseif (preg_match('#Opera.([a-zA-Z0-9.]+)#i', $ua, $matches)) {  
   $browser = 'Opera ' . $matches[1];  
 } elseif (preg_match('#TencentTraveler ([a-zA-Z0-9.]+)#i', $ua, $matches)) {  
   $browser = '腾讯TT浏览器 ' . $matches[1];  
 } elseif (preg_match('#UCWEB([a-zA-Z0-9.]+)#i', $ua, $matches)) {  
   $browser = 'UCWEB ' . $matches[1];  
 } elseif (preg_match('#MSIE ([a-zA-Z0-9.]+)#i', $ua, $matches)) {  
   $browser = 'Internet Explorer ' . $matches[1];  
 } elseif (preg_match('#Edge/12.0#i',$ua,$matches)) {  
   $browser = 'Spartan';  
 } elseif (preg_match('#(Firefox|Phoenix|Firebird|BonEcho|GranParadiso|Minefield|Iceweasel)/([a-zA-Z0-9.]+)#i', $ua, $matches)) {  
   $browser = 'Firefox ' . $matches[2];  
 } else {  
   $browser = '吾爱笔记御用浏览器';  
 }  
 return $os . " | " . $browser;  
}  
//说说
 add_action('init', 'my_custom_init'); 
 function my_custom_init() { 
    $labels = array( 'name' => '说说', 
        'singular_name' => 'singularname',
        'add_new' => '发表说说', 
        'add_new_item' => '发表说说', 
        'edit_item' => '编辑说说', 
        'new_item' => '新说说', 
        'view_item' => '查看说说',
        'search_items' => '搜索说说', 
        'not_found' => '暂无说说', 
        'not_found_in_trash' => '没有已遗弃的说说',
        'parent_item_colon' => '',
        'menu_name' => '说说' );
     $args = array( 'labels' => $labels, 
        'public' => true, 
        'publicly_queryable' => true,
        'show_ui' => true, 
        'show_in_menu' => true, 
        'query_var' => true, 
        'rewrite' => true, 
        'capability_type' => 'post', 
        'has_archive' => true, 
        'hierarchical' => false, 
        'menu_position' => null, 
        'supports' => array('title','editor','author') ); register_post_type('shuoshuo',$args); 
 }
 //归档文章
 function specs_archives_list() {
    if( !$output = get_option('specs_archives_list') ){
        $output = '';
        $the_query = new WP_Query( 'posts_per_page=-1&ignore_sticky_posts=1' ); //update: 加上忽略置顶文章
        $year=0; $mon=0; $i=0; $j=0;
        while ( $the_query->have_posts() ) : $the_query->the_post();
            $year_tmp = get_the_time('Y');
            $mon_tmp = get_the_time('m');
            $y=$year; $m=$mon;
            if ($mon != $mon_tmp && $mon > 0) $output .= '</ul></li>';
            if ($year != $year_tmp && $year > 0) $output .= '</ul>';
            if ($year != $year_tmp) {
                $year = $year_tmp;
                $output .= '<h3 class="al_year">'. $year .' 年</h3><ul class="al_mon_list">'; //输出年份
            }
            if ($mon != $mon_tmp) {
                $mon = $mon_tmp;
                $output .= '<li><span class="al_mon">'. $mon .' 月</span><ul class="al_post_list">'; //输出月份
            }
            $output .= '<li>'. get_the_time('d日: ') .'<a href="'. get_permalink() .'" title="'.get_the_title().'">'. get_the_title() .'</a> <em>('. get_comments_number('0', '1', '%') .')</em></li>'; //输出文章日期和标题
        endwhile;
        wp_reset_postdata();
        $output .= '</ul></li></ul>';
        update_option('specs_archives_list', $output);
    }
    echo $output;
}
function clear_archives_cache() {
    update_option('specs_archives_list', ''); // 清空 specs_archives_list
}
add_action('save_post', 'clear_archives_cache'); // 新发表文章/修改文章时

    //新标签打开文章链接
function ist_admin_aritical_ctrlenter() {
    echo '<script type="text/javascript">
    var postlink = document.getElementById("view-post-btn").getElementsByClassName("button button-small");
        for(var i=0;i<postlink.length;i++)
    { postlink[i].target = "_blank"; }
        </script>';
};
add_action('admin_footer', 'ist_admin_aritical_ctrlenter');



?>










